import { applyMiddleware, compose, createStore } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { makeRootReducer } from './reducers';

const logger = store => next => action => {
  console.log('dispatching', action);
  const result = next(action);
  console.log('next state', store.getState());
  return result;
};

const crashReporter = store => next => action => {
  try {
    return next(action);
  } catch (err) {
    console.error('Caught an exception:[', err, ']');
    console.error('Action:[', action, ']');
    console.error('State:[', store.getState(), ']');
    throw err;
  }
};

const structureStore = (initialState = {}) => {
  const middleware = [];
  if (process.env.NODE_ENV === 'development') {
    middleware.push(logger);
    middleware.push(crashReporter);
  }
  middleware.push(thunkMiddleware);

  const enhancers = [];

  const store = createStore(
    makeRootReducer(),
    initialState,
    compose(
      applyMiddleware(...middleware),
      ...enhancers
    )
  );
  store.asyncReducers = {};

  return store;
};

export default structureStore
